#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QHostAddress>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    setWindowTitle("客户端");
    ui->port->setText("8899");//set the port
    ui->ip->setText("127.0.0.1");

    //创建监听的服务器对象
    m_tcp = new QTcpSocket(this);

    ui->disServer->setDisabled(true);
    ui->sndMsg->setDisabled(true);

    connect(m_tcp,&QTcpSocket::readyRead,this,[=](){
      QByteArray data = m_tcp->readAll();
      ui->Record->append("服务器："+ data);
    });

    connect(m_tcp,&QTcpSocket::disconnected,this,[=](){
        m_tcp->close();
        //m_tcp->deleteLater();
        m_State->setPixmap(QPixmap(":/disconnected.jpg").scaled(20,20));
        ui->Record->append("已经断开与服务器的连接...");
        ui->sndMsg->setDisabled(true);
        ui->disServer->setDisabled(true);
        ui->conServer->setEnabled(true);
    });

    connect(m_tcp,&QTcpSocket::connected,this,[=](){
        m_State->setPixmap(QPixmap(":/connected.jpg").scaled(20,20));
        ui->Record->append("已经成功连接到服务器...");
        ui->sndMsg->setEnabled(true);
        ui->conServer->setDisabled(true);
        ui->disServer->setEnabled(true);
    });


    //状态栏
    m_State = new QLabel;
    m_State->setPixmap(QPixmap(":/disconnected.jpg").scaled(20,20));
    ui->statusbar->addWidget(new QLabel("连接对象："));
    ui->statusbar->addWidget(m_State);
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_conServer_clicked()
{
    QString ip = ui->ip->text();
    unsigned short port = ui->port->text().toUShort();
    m_tcp->connectToHost(QHostAddress(ip),port);

}

void MainWindow::on_sndMsg_clicked()
{
   QString msg = ui->msg->toPlainText();
   m_tcp->write(msg.toUtf8());
   ui->Record->append("客户端：" + msg);
}

void MainWindow::on_disServer_clicked()
{
    m_tcp->close();
    ui->conServer->setEnabled(true);
    ui->disServer->setDisabled(true);
}
